using Castle.Windsor;
using System;
using Castle.MicroKernel.Registration;
using System.IO;

namespace WyUnity.Utility.IOC
{
    public class WindsorObjectContainer : IObjectContainer
    {
        private IWindsorContainer _container;

        public WindsorObjectContainer()
        {
            var path = FileHelper.GetFilePath("Windsor.config");
            if (File.Exists(path))
                _container = new WindsorContainer(path);
            else
                _container = new WindsorContainer();


        }

        [System.Diagnostics.DebuggerHidden]
        public void RegistSingleton<T>(string key, T obj)
        {
            _container.Register(Component.For(typeof(T)).Instance(obj).LifeStyle.Singleton.Named(key));
        }

        [System.Diagnostics.DebuggerHidden]
        public void Regist<T>(string key) where T : class
        {
            _container.Register(
                    Component.For<T>()
                    .Named(key)
                );
        }

        [System.Diagnostics.DebuggerHidden]
        public void Regist<T>() where T : class
        {
            _container.Register(
                    Component.For<T>()

                );
        }

        [System.Diagnostics.DebuggerHidden]
        public void Regist<I, T>(Type[] interceptors)
            where T : class,I
            where I : class
        {
            if (interceptors == null || interceptors.Length == 0)
            {
                _container.Register(Component.For<I>().ImplementedBy<T>().LifeStyle.Singleton);
            }
            else
            {
                _container.Register(
                    Component.For<I>()
                    .ImplementedBy<T>()
                    .Interceptors(interceptors)
                    .LifestyleSingleton()
                );
            }
        }

        public void Remove<T>(string key)
        {
            _container.Release((this as IObjectContainer).Get<T>(key));
        }

        public void Remove<T>()
        {
            throw new System.NotImplementedException();
        }

        [System.Diagnostics.DebuggerHidden]
        public object Get(Type type)
        {
            return _container.Resolve(type);
        }
        [System.Diagnostics.DebuggerHidden]
        T IObjectContainer.Get<T>()
        {
            return _container.Resolve<T>();
        }

        [System.Diagnostics.DebuggerHidden]
        T IObjectContainer.Get<T>(string key)
        {
            return _container.Resolve<T>(key);
        }

        [System.Diagnostics.DebuggerHidden]
        public T[] GetAll<T>()
        {
            return _container.ResolveAll<T>();
        }

        public object Container
        {
            get { return _container; }
        }
    }
}